package com.hoshiicloud.user.service.impl.usercenter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.user.entity.usercenter.MemberIntegration;
import com.hoshiicloud.user.entity.usercenter.PlatConsumer;
import com.hoshiicloud.user.feign.IdGeneratorService;
import com.hoshiicloud.user.mapper.usercenter.MemberIntegrationMapper;
import com.hoshiicloud.user.service.usercenter.IMemberIntegrationService;
import com.hoshiicloud.user.service.usercenter.IPlatConsumerService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户积分Service接口实现类
 *
 * @author : yangcheng
 * @date : 2019/5/13 10:36
 * @mail : maiboyc@163.com
 **/
@Service
public class MemberIntegrationServiceImpl extends ServiceImpl<MemberIntegrationMapper, MemberIntegration> implements IMemberIntegrationService {

    // Id生成Service
    @Autowired
    private IdGeneratorService idGeneratorService;

    // 用户基本信息Service
    @Autowired
    private IPlatConsumerService platMemberService;

    /**
     * 根据id获取
     * @param id ID
     * @return MemberIntegration
     */
    @Cacheable(cacheNames = "memberIntegration", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "用户管理-用户积分管理-根据ID查询用户积分信息")
    @Override
    public MemberIntegration getById(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * 根据一组id
     * @param ids id组
     * @return List<MemberIntegration>
     */
    @Cacheable(cacheNames = "memberIntegration", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#ids")
    @Logable(authName = "用户管理-用户积分管理-根据ID组查询用户积分信息")
    @Override
    public List<MemberIntegration> getByIds(List<Long> ids) {
        return baseMapper.selectBatchIds(ids);
    }

    /**
     * 保存
     * @param entity 实体对象
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "memberIntegration", allEntries = true)
    @Logable(authName = "用户管理-用户积分管理-新增用户积分信息")
    @Override
    public Long insert(MemberIntegration entity) throws ServiceException {
        // 调用主键生成微服务生成主键
        String id = idGeneratorService.queryGeneratorId();
        if (id == null) {
            throw new ServiceException(CommonError.error("新增用户积分失败,生成ID主键失败"));
        }
        // 调用用户基本信息Service检查用户账户信息是否存在
        PlatConsumer platConsumer = platMemberService.getById(entity.getUserId());
        if (platConsumer == null) {
            throw new ServiceException(CommonError.error("新增用户积分失败，没有找到对应的用户基本信息"));
        }
        // 自动生成id，创建日期 修改日期 创建人 修改人 删除标识
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setCreatedBy("admin");// 需要拿当前的登录人
        entity.setUpdatedBy("admin");// 需要拿当前的登录人
        entity.setDeleted(0);
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增用户积分失败"));
        }
        return entity.getId();
    }

    /**
     * 修改
     * @param entity 实体对象
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "memberIntegration", allEntries = true)
    @Logable(authName = "用户管理-用户积分管理-修改用户积分信息")
    @Override
    public Long update(MemberIntegration entity) throws ServiceException {
        // 自动填入修改时间 修改人
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setUpdatedBy("admin1");// 需要拿当前的登录人
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改用户积分信息失败"));
        }
        return entity.getId();
    }

    /**
     * 查询
     * @param entity 查询参数实体
     * @return IPage<MemberIntegration>
     */
    @Cacheable(cacheNames = "memberIntegration", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#entity.pageIndex+':'+#entity.pageSize+':'+#entity.userId+':'+#entity.integrationno+':'+#entity.source+':'+#entity.status")
    @Logable(authName = "用户管理-用户积分管理-分页查询用户积分信息")
    @Override
    public IPage<MemberIntegration> List(MemberIntegration entity) {
        QueryWrapper<MemberIntegration> queryWrapper = new QueryWrapper();
        IPage<MemberIntegration> page = new Page();
        if(entity.getPageIndex() != null) {
            page.setCurrent(entity.getPageIndex());
        }
        if(entity.getPageSize() != null){
            page.setSize(entity.getPageSize());
        }
        if (entity.getUserId() != null) {
            queryWrapper.eq("user_id", entity.getUserId());
        }
        if (StringUtils.isNotEmpty(entity.getIntegrationno())) {
            queryWrapper.like("integrationno", entity.getIntegrationno());
        }
        if (null != entity.getSource()) {
            queryWrapper.eq("source", entity.getSource());
        }
        if (null != entity.getStatus()) {
            queryWrapper.eq("status", entity.getStatus());
        }
        // 默认查询只查询未逻辑删除的数据
        queryWrapper.eq("deleted", 0);
        return baseMapper.selectPage(page,queryWrapper);
    }

    /**
     * 删除
     * @param id ID
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "memberIntegration", allEntries = true)
    @Logable(authName = "用户管理-用户积分管理-删除用户积分信息")
    @Override
    public boolean delete(Long id) throws ServiceException {
        MemberIntegration entity = this.getById(id);
        entity.setDeleted(1);
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除用户积分失败"));
        } else {
            return true;
        }
    }

    /**
     * 根据条件查询消费者积分
     * @param entity 消费者ID
     * @return IPage<MemberIntegration>
     */
    @Cacheable(cacheNames = "memberIntegration", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+':'+#entity.userId+':'+#entity.integrationno+':'+#entity.source+':'+#entity.status")
    @Logable(authName = "用户管理-用户积分管理-根据参数查询查询用户积分信息")
    @Override
    public List<MemberIntegration> getMemberIntegrations(MemberIntegration entity) {
        QueryWrapper<MemberIntegration> queryWrapper = new QueryWrapper();
        if (entity.getUserId() != null) {
            queryWrapper.eq("user_id", entity.getUserId());
        }
        if (StringUtils.isNotEmpty(entity.getIntegrationno())) {
            queryWrapper.like("integrationno", entity.getIntegrationno());
        }
        if (null != entity.getSource()) {
            queryWrapper.eq("source", entity.getSource());
        }
        if (null != entity.getStatus()) {
            queryWrapper.eq("status", entity.getStatus());
        }
        // 默认查询只查询未逻辑删除的数据
        queryWrapper.eq("deleted", 0);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据消费者ID获取消费者积分
     * @param consumerId 消费者ID
     * @return MemberIntegration
     */
    @Cacheable(cacheNames = "memberIntegration", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#consumerId")
    @Logable(authName = "用户管理-用户积分管理-根据消费者ID查询用户积分信息")
    @Override
    public MemberIntegration getMemberIntegrationsByConsumerId(Long consumerId) {
        QueryWrapper<MemberIntegration> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",consumerId);
        // 默认查询只查询未逻辑删除的数据
        queryWrapper.eq("deleted", 0);
        List<MemberIntegration> memberIntegrations = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(memberIntegrations)) {
            return memberIntegrations.get(0);
        } else {
            return null;
        }
    }

}